package com.starsea.book.ui.book.info

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SpanUtils
import com.starsea.book.R
import com.starsea.book.base.VMBaseActivity
import com.starsea.book.constant.Theme
import com.starsea.book.data.appDb
import com.starsea.book.data.entities.Book
import com.starsea.book.databinding.ActivityBookInfoBinding
import com.starsea.book.help.book.*
import com.starsea.book.help.config.AppConfig
import com.starsea.book.lib.theme.accentColor
import com.starsea.book.lib.theme.backgroundColor
import com.starsea.book.lib.theme.bottomBackground
import com.starsea.book.model.BookCover
import com.starsea.book.model.ReadBook
import com.starsea.book.ui.book.audio.AudioPlayActivity
import com.starsea.book.ui.book.info.edit.BookInfoEditActivity
import com.starsea.book.ui.book.read.ReadBookActivity
import com.starsea.book.ui.book.search.SearchActivity
import com.starsea.book.ui.book.toc.TocActivityResult
import com.starsea.book.ui.file.HandleFileContract
import com.starsea.book.ui.newpage.CommentListAllActivity
import com.starsea.book.ui.newpage.LoginActivity
import com.starsea.book.ui.newpage.adapter.BookDetailsCommentAdapter
import com.starsea.book.ui.newpage.entity.BaseEntity
import com.starsea.book.ui.newpage.entity.BookInfoEntity
import com.starsea.book.ui.newpage.utils.finialDouble
import com.starsea.book.ui.newpage.utils.loadNormalImage
import com.starsea.book.ui.widget.dialog.WaitDialog
import com.starsea.book.utils.*
import com.starsea.book.utils.viewbindingdelegate.viewBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class BookInfoActivity :
    VMBaseActivity<ActivityBookInfoBinding, BookInfoViewModel>(toolBarTheme = Theme.Dark) {


    override val binding by viewBinding(ActivityBookInfoBinding::inflate)
    override val viewModel by viewModels<BookInfoViewModel>()

//    var mHelper: SwipeBackActivityHelper? = null

    var mAdapter: BookDetailsCommentAdapter? = null


    private val readBookResult = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) {
        viewModel.upBook(intent)
        if (it.resultCode == RESULT_OK) {
            viewModel.inBookshelf = true
//      upTvBookshelf()
        }
    }


    private var tocChanged = false
    private var chapterChanged = false
    private val waitDialog by lazy { WaitDialog(this) }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        viewModel.initData(intent)
        binding.ivFinish?.setOnClickListener { finish() }
        initViewEvent()


//    hideTitleBar()
        BarUtils.addMarginTopEqualStatusBarHeight(binding.llTitle!!)

        val bookId = intent.getStringExtra("bookId") ?: ""
        binding.comments?.setOnClickListener {
            startActivity<CommentListAllActivity> {
                putExtra("bookId", bookId)
            }
        }
//    viewModel.getBookInfo(bookId)

//    swipeBackLayout.setEdgeSize(0)
//    swipeBackLayout.setSensitivity(mContext,0.1f)
        mAdapter = BookDetailsCommentAdapter(this)

        binding.rvComment!!.layoutManager = LinearLayoutManager(this)
        binding.rvComment!!.adapter = mAdapter
        mAdapter!!.add("")
        mAdapter!!.add("")
        mAdapter!!.add("")
        mAdapter!!.add("")
        mAdapter!!.add("")
        mAdapter!!.add("")
        mAdapter!!.add("")
        mAdapter!!.add("")
        mAdapter!!.add("")




        viewModel.bookInfoResult.observe(this) {
            if (it.status == 200) {
                showBook(it.data!!)
            } else if (it.status == 401) {
                toastOnUi("登录过期，请重新登录")
//        .start(this@BookDetailsActivity)
                startActivity<LoginActivity>()
            } else {
                toastOnUi(it.msg)
            }
        }

        viewModel.addSherfResult.observe(this@BookInfoActivity) {
            if (it.status == 200) {
                ReadBook.inBookshelf = true
                setResult(Activity.RESULT_OK)
                toastOnUi("加入书架成功")
                binding.rtvAddShelf!!.text = "已加入"
            } else if (it.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(this@BookInfoActivity)
            } else {
                toastOnUi(it.msg)
            }
        }
    }

    private fun showBook(it: BookInfoEntity) {
        binding.ivBookCover!!.loadNormalImage(this, it.bookCover ?: "")
        binding.tvBookAuthor!!.text = "作者：${it.authorName ?: ""}"
        binding.tvBookTitle!!.text = it.bookTitle ?: ""

        binding.tvSocre!!.text =
            SpanUtils().append((it.bookScore ?: 0.0).finialDouble())
                .append("分")
                .setFontSize(12, true).create()
        binding.tvScoreCount!!.text = "${it.scoreCount}点评"
        binding.tvReadScore!!.text =
            SpanUtils().append(
                (if ((it.pvCount ?: 0) > 10000) ((it.pvCount
                    ?: 0) / 10000.0).finialDouble() else it.pvCount ?: 0).toString()
            )
                .append(if ((it.pvCount ?: 0) > 10000) "万人" else "人")
                .setFontSize(12, true).create()

        //0连载1完结2停更
        binding.tvBookState!!.text =
            if (it.bookState == 0) "连载" else if (it.bookState == 1) "完结" else "停更"

        binding.tvFinishScore!!.text =
            SpanUtils().append(
                (if ((it.wordCount ?: 0) > 10000) ((it.wordCount
                    ?: 0) / 10000.0).finialDouble() else it.wordCount ?: 0).toString()
            )
                .append(if ((it.wordCount ?: 0) > 10000) "万字" else "字")
                .setFontSize(12, true).create()

        binding.tvBookDesc!!.text = it.bookDesc

//        binding.rtvAddShelf!!.text = "已加入"


    }

    var menu_delete: MenuItem? = null
    var menu_add: MenuItem? = null

    override fun observeLiveBus() {
        viewModel.actionLive.observe(this) {
            when (it) {
                "selectBooksDir" -> localBookTreeSelect.launch {
                    title = getString(R.string.select_book_folder)
                }
            }
        }
    }

    private val localBookTreeSelect = registerForActivityResult(HandleFileContract()) {
        it.uri?.let { treeUri ->
            AppConfig.defaultBookTreeUri = treeUri.toString()
        }
    }


    private fun initViewEvent() = binding.run {
        rtvRead!!.setOnClickListener {
            viewModel.getBook()?.let { book ->
                readBook(book, false)
            }
        }

        rtvAddShelf!!.setOnClickListener {
            viewModel.getBook()?.let { book ->
                viewModel.addToShelf(book.bookUrl)
            }

        }
        binding.readAloud?.setOnClickListener {
            viewModel.getBook()?.let { book ->
                readBook(book, true)
            }
        }
    }

    private fun openChapterList() {

        viewModel.getBook()?.let {
            LogUtils.e(">>>>> ", "bookUrl = " + it.bookUrl)
            tocActivityResult.launch(it.bookUrl)
        }
    }


    private val tocActivityResult = registerForActivityResult(TocActivityResult()) {
        it?.let {
            viewModel.getBook(false)?.let { book ->
                lifecycleScope.launch {
                    withContext(Dispatchers.IO) {
                        book.durChapterIndex = it.first
                        book.durChapterPos = it.second
                        chapterChanged = it.third
                        appDb.bookDao.update(book)
                    }
                    viewModel.chapterListData.value?.let { chapterList ->
//                        binding.tvToc.text =
//                            getString(R.string.toc_s, chapterList[book.durChapterIndex].title)
                    }
                    startReadActivity(book, false)
                }
            }
        } ?: let {
            if (!viewModel.inBookshelf) {
                viewModel.delBook()
            }
        }
    }

    private fun readBook(book: Book, isReadAloud: Boolean) {
        if (!viewModel.inBookshelf) {
            viewModel.saveBook(book) {
                viewModel.saveChapterList {
                    startReadActivity(book, isReadAloud)
                }
            }
        } else {
            viewModel.saveBook(book) {
                startReadActivity(book, isReadAloud)
            }
        }
    }

    private fun startReadActivity(book: Book, isReadAloud: Boolean) {
        when {
            book.isAudio -> readBookResult.launch(
                Intent(this, AudioPlayActivity::class.java)
                    .putExtra("bookUrl", book.bookUrl)
                    .putExtra("inBookshelf", viewModel.inBookshelf)
            )

            else -> readBookResult.launch(
                Intent(this, ReadBookActivity::class.java)
                    .putExtra("bookUrl", book.bookUrl)
                    .putExtra("inBookshelf", viewModel.inBookshelf)
                    .putExtra("tocChanged", tocChanged)
                    .putExtra("chapterChanged", chapterChanged)
                    .putExtra("isReadAloud", isReadAloud)
            )
        }
        tocChanged = false
    }
//
//    private val tocActivityResult = registerForActivityResult(TocActivityResult()) {
//        it?.let {
//            viewModel.getBook(false)?.let { book ->
//                lifecycleScope.launch {
//                    withContext(IO) {
//                        book.durChapterIndex = it.first
//                        book.durChapterPos = it.second
//                        chapterChanged = it.third
//                        appDb.bookDao.update(book)
//                    }
//                    viewModel.chapterListData.value?.let { chapterList ->
////                        binding.tvToc.text =
////                            getString(R.string.toc_s, chapterList[book.durChapterIndex].title)
//                    }
//                    startReadActivity(book)
//                }
//            }
//        } ?: let {
//            if (!viewModel.inBookshelf) {
//                viewModel.delBook()
//            }
//        }
//    }
//    private val localBookTreeSelect = registerForActivityResult(HandleFileContract()) {
//        it.uri?.let { treeUri ->
//            AppConfig.defaultBookTreeUri = treeUri.toString()
//        }
//    }
//
//    private val readBookResult = registerForActivityResult(
//        ActivityResultContracts.StartActivityForResult()
//    ) {
//        viewModel.upBook(intent)
//        if (it.resultCode == RESULT_OK) {
//            viewModel.inBookshelf = true
//            upTvBookshelf()
//        }
//    }
//    private val infoEditResult = registerForActivityResult(
//        StartActivityContract(BookInfoEditActivity::class.java)
//    ) {
//        if (it.resultCode == RESULT_OK) {
//            viewModel.upEditBook()
//        }
//    }
//
//    private var tocChanged = false
//    private var chapterChanged = false
//    private val waitDialog by lazy { WaitDialog(this) }
//
//    //    private var editMenuItem: MenuItem? = null
//    private val book get() = viewModel.getBook(false)
//
//    override val binding by viewBinding(ActivityBookInfoBinding::inflate)
//    override val viewModel by viewModels<BookInfoViewModel>()
//
//    @SuppressLint("PrivateResource")
//    override fun onActivityCreated(savedInstanceState: Bundle?) {
//        binding.titleBar.setBackgroundResource(R.color.transparent)
//        binding.refreshLayout?.setColorSchemeColors(accentColor)
//        binding.arcView.setBgColor(backgroundColor)
//        binding.llInfo.setBackgroundColor(backgroundColor)
//        binding.flAction.setBackgroundColor(bottomBackground)
////        binding.tvShelf.setTextColor(getPrimaryTextColor(ColorUtils.isColorLight(bottomBackground)))
////        binding.tvToc.text = getString(R.string.toc_s, getString(R.string.loading))
//
////        viewModel.bookData.observe(tax3his) { showBook(it) }
//
//        viewModel.bookInfoResult.observe(this) {
//            if (it.status == 200) {
//                showBook(it)
//            } else if (it.status == 401) {
//                toastOnUi("登录过期，请重新登录")
//                LoginActivity.start(this@BookInfoActivity)
//            } else {
//                toastOnUi(it.msg)
//            }
//
//        }
//
////        viewModel.bookCommentTotalNumResult.observe(this) {
////            if (it.status == 200) {
////                binding.tvScorePerson?.text = "${it.data}人点评"
////            } else if (it.status == 401) {
////                toastOnUi("登录过期，请重新登录")
////                LoginActivity.start(this@BookInfoActivity)
////            } else {
////                toastOnUi(it.msg)
////            }
////        }
//
//        viewModel.addSherfResult.observe(this) {
//            if (it.status == 200) {
//                viewModel.inBookshelf = true
//                toastOnUi("加入书架成功")
//            } else if (it.status == 401) {
//                toastOnUi("登录过期，请重新登录")
//                LoginActivity.start(this@BookInfoActivity)
//            } else {
//                toastOnUi(it.msg)
//            }
//        }
//
//        viewModel.bookSectionListResult.observe(this) {
//
//        }
//
//        viewModel.chapterListData.observe(this) {
////            upLoading(false, it)
//        }
//        viewModel.waitDialogData.observe(this) {
//            upWaitDialogStatus(it)
//        }
////        viewModel.getCommentList(intent.getStringExtra("bookId") ?: "")
//
//        viewModel.initData(intent)
//
//        initViewEvent()
//
//    }
//
//    override fun onResume() {
//        super.onResume()
////        viewModel.getCommentTotalNum(intent.getStringExtra("bookId") ?: "")
//    }
//
//    var menu_delete: MenuItem? = null
//    var menu_add: MenuItem? = null
//
//    override fun onCompatCreateOptionsMenu(menu: Menu): Boolean {
//        menuInflater.inflate(R.menu.book_info, menu)
//        menu_delete = menu.findItem(R.id.menu_delete)
//        menu_add = menu.findItem(R.id.menu_delete)
//        return super.onCompatCreateOptionsMenu(menu)
//    }
//
//    override fun onMenuOpened(featureId: Int, menu: Menu): Boolean {
////        menu.findItem(R.id.menu_can_update)?.isChecked =
////            viewModel.bookData.value?.canUpdate ?: true
////        menu.findItem(R.id.menu_split_long_chapter)?.isChecked =
////            viewModel.bookData.value?.getSplitLongChapter() ?: true
////        menu.findItem(R.id.menu_login)?.isVisible =
////            false
////        menu.findItem(R.id.menu_set_source_variable)?.isVisible =
////            false
////        menu.findItem(R.id.menu_set_book_variable)?.isVisible =
////            false
////        menu.findItem(R.id.menu_can_update)?.isVisible =
////            false
////        menu.findItem(R.id.menu_split_long_chapter)?.isVisible =
////           false
////        menu.findItem(R.id.menu_upload)?.isVisible =
////            false
////        menu.findItem(R.id.menu_delete_alert)?.isVisible =
////            false
////        menu.findItem(R.id.menu_delete_alert)?.isChecked =
////            LocalConfig.bookInfoDeleteAlert
//        return super.onMenuOpened(featureId, menu)
//    }
//
//    override fun onCompatOptionsItemSelected(item: MenuItem): Boolean {
//        when (item.itemId) {
////            R.id.menu_edit -> {
////                viewModel.getBook()?.let {
////                    infoEditResult.launch {
////                        putExtra("bookUrl", it.bookUrl)
////                    }
////                }
////            }
//            R.id.menu_mulu -> {
//                if (viewModel.chapterListData.value.isNullOrEmpty()) {
//                    toastOnUi(R.string.chapter_list_empty)
//                    return super.onCompatOptionsItemSelected(item)
//                }
//                toMuLu()
//            }
//
//            R.id.menu_add -> {
//                if (viewModel.inBookshelf) {
//                    toastOnUi("已加入书架")
//                    return super.onCompatOptionsItemSelected(item)
//                }
//                viewModel.addToShelf(bookId = intent.getStringExtra("bookId") ?: "", "", "")
//            }
//
//            R.id.menu_delete -> {
////                viewModel.addToShelf(bookId = intent.getStringExtra("bookId") ?: "", "", "")
//            }
//
////            R.id.menu_share_it -> {
////                viewModel.getBook()?.let {
////                    val bookJson = GSON.toJson(it)
////                    val shareStr = "${it.bookUrl}#$bookJson"
////                    shareWithQr(shareStr, it.name)
////                }
////            }
//
////            R.id.menu_refresh -> {
////                refreshBook()
////            }
//
////            R.id.menu_login -> viewModel.bookSource?.let {
////                startActivity<SourceLoginActivity> {
////                    putExtra("type", "bookSource")
////                    putExtra("key", it.bookSourceUrl)
////                }
////            }
//
////            R.id.menu_top -> viewModel.topBook()
////            R.id.menu_set_source_variable -> setSourceVariable()
////            R.id.menu_set_book_variable -> setBookVariable()
////            R.id.menu_copy_book_url -> viewModel.getBook()?.bookUrl?.let {
////                sendToClip(it)
////            }
//
////            R.id.menu_copy_toc_url -> viewModel.getBook()?.tocUrl?.let {
////                sendToClip(it)
////            }
//
////            R.id.menu_can_update -> {
////                viewModel.getBook()?.let {
////                    it.canUpdate = !it.canUpdate
////                    if (viewModel.inBookshelf) {
////                        viewModel.saveBook(it)
////                    }
////                }
////            }
//
////            R.id.menu_clear_cache -> viewModel.clearCache()
////            R.id.menu_log -> showDialogFragment<AppLogDialog>()
////            R.id.menu_split_long_chapter -> {
//////                upLoading(true)
////                tocChanged = true
////                viewModel.getBook()?.let {
////                    it.setSplitLongChapter(!item.isChecked)
////                    viewModel.loadBookInfo(it, false)
////                }
////                item.isChecked = !item.isChecked
////                if (!item.isChecked) longToastOnUi(R.string.need_more_time_load_content)
////            }
//
////            R.id.menu_delete_alert -> LocalConfig.bookInfoDeleteAlert = !item.isChecked
////            R.id.menu_upload -> {
////                viewModel.getBook()?.let { book ->
////                    book.getRemoteUrl()?.let {
////                        alert(R.string.draw, R.string.sure_upload) {
////                            okButton {
////                                upLoadBook(book)
////                            }
////                            cancelButton()
////                        }
////                    } ?: upLoadBook(book)
////                }
////            }
//        }
//        return super.onCompatOptionsItemSelected(item)
//    }
//
//    override fun observeLiveBus() {
//        viewModel.actionLive.observe(this) {
//            when (it) {
//                "selectBooksDir" -> localBookTreeSelect.launch {
//                    title = getString(R.string.select_book_folder)
//                }
//            }
//        }
//    }
//
//    private fun refreshBook() {
////        upLoading(true)
//        viewModel.getBook()?.let {
//            viewModel.refreshBook(it)
//        }
//    }
//
////    private fun upLoadBook(
////        book: Book,
////        bookWebDav: RemoteBookWebDav? = AppWebDav.defaultBookWebDav
////    ) {
////        lifecycleScope.launch {
////            waitDialog.setText("上传中.....")
////            waitDialog.show()
////            try {
////                bookWebDav
////                    ?.upload(book)
////                    ?: throw NoStackTraceException("未配置webDav")
////                //更新书籍最后更新时间,使之比远程书籍的时间新
////                book.lastCheckTime = System.currentTimeMillis()
////                viewModel.saveBook(book)
////            } catch (e: Exception) {
////                toastOnUi(e.localizedMessage)
////            } finally {
////                waitDialog.dismiss()
////            }
////        }
////    }
//
//    private fun showBook(book: BaseEntity<BookInfoEntity>) = binding.run {
//        showCover(book)
//        tvName.text = book.data!!.bookTitle
//        tvAuthor.text = getString(R.string.author_show, book.data!!.authorName ?: "佚名")
//
//        tvScore!!.text = book.data!!.bookScore.toString()
//        tvScorePerson!!.text = "${book.data!!.scoreCount}人点评"
//        tvReadNum!!.text = "${book.data!!.pvCount}人"
//        tvWordCount!!.text =
//            "${if (book.data!!.wordCount > 10000) "${(book.data!!.wordCount / 10000.0).finialDouble()}万" else "${book.data!!.wordCount}"}"
////        0连载1完结2停更
//        tvBookStatus!!.text =
//            if (book.data!!.bookState == 0) "连载" else if (book.data!!.bookState == 1) "完结" else "停更"
//        tvIntro.text = book.data!!.bookDesc
//
////        是否已加入书架 0 否 1 是
////        var menu_delete: MenuItem? = null
////        var menu_add: MenuItem? = null
////        menu_add!!.setVisible(book.data!!.bookShelfFlag == 0)
////        menu_delete!!.setVisible(book.data!!.bookShelfFlag == 1)
//
////        tvOrigin.text = getString(R.string.origin_show, book.originName)
////        tvLasted.text = getString(R.string.lasted_show, book.latestChapterTitle)
////        tvIntro.text = book.getDisplayIntro()
////        llToc?.visible(!book.isWebFile)
//        upTvBookshelf()
//
////        upGroup(book.group)
//    }
//
//    private fun showCover(book: BaseEntity<BookInfoEntity>) {
//        binding.ivCover.load(
//            book.data!!.bookCover, book.data!!.bookTitle,
//            book.data!!.authorName, false, ""
//        )
//        if (!AppConfig.isEInkMode) {
//            BookCover.loadBlur(this, book.data!!.bookCover)
//                .into(binding.bgBook)
//        }
//    }
////
////    private fun upLoading(isLoading: Boolean, chapterList: List<BookChapter>? = null) {
////        when {
////            isLoading -> {
////                binding.tvToc.text = getString(R.string.toc_s, getString(R.string.loading))
////            }
////
////            chapterList.isNullOrEmpty() -> {
////                binding.tvToc.text = getString(
////                    R.string.toc_s,
////                    getString(R.string.error_load_toc)
////                )
////            }
////
////            else -> {
////                viewModel.bookData.value?.let {
////                    if (it.durChapterIndex < chapterList.size) {
////                        binding.tvToc!!.text =
////                            getString(R.string.toc_s, chapterList[it.durChapterIndex].title)
////                    } else {
////                        binding.tvToc.text = getString(R.string.toc_s, chapterList.last().title)
////                    }
////                    binding.tvLasted.text =
////                        getString(R.string.lasted_show, chapterList.last().title)
////                }
////            }
////        }
////    }
//
//    private fun upTvBookshelf() {
////        if (viewModel.inBookshelf) {
////            binding.tvShelf.text = getString(R.string.remove_from_bookshelf)
////        } else {
////            binding.tvShelf.text = getString(R.string.add_to_bookshelf)
////        }
////        editMenuItem?.isVisible = false
//    }
////
////    private fun upGroup(groupId: Long) {
////        viewModel.loadGroup(groupId) {
////            if (it.isNullOrEmpty()) {
////                binding.tvGroup.text = if (book?.isLocal == true) {
////                    getString(R.string.group_s, getString(R.string.local_no_group))
////                } else {
////                    getString(R.string.group_s, getString(R.string.no_group))
////                }
////            } else {
////                binding.tvGroup.text = getString(R.string.group_s, it)
////            }
////        }
////    }
//
//    private fun initViewEvent() = binding.run {
////        ivCover.setOnClickListener {
////            viewModel.getBook()?.let {
////                showDialogFragment(
////                    ChangeCoverDialog(it.name, it.author)
////                )
////            }
////        }
////        ivCover.setOnLongClickListener {
////            viewModel.getBook()?.getDisplayCover()?.let { path ->
////                showDialogFragment(PhotoDialog(path))
////            }
////            true
////        }
//
//        tvScore?.setOnClickListener {
//            startActivity<CommentListAllActivity> {
//                putExtra("bookId", intent.getStringExtra("bookId") ?: "")
//            }
//        }
//        tvScorePerson?.setOnClickListener {
//            startActivity<CommentListAllActivity> {
//                putExtra("bookId", intent.getStringExtra("bookId") ?: "")
//            }
//        }
//
//        tvAddShelf?.setOnClickListener {
//            if (viewModel.inBookshelf) {
//                toastOnUi("已加入书架")
//                return@setOnClickListener
//            }
//            viewModel.addToShelf(bookId = intent.getStringExtra("bookId") ?: "", "", "")
//        }
//
//        tvRead.setOnClickListener {
//            viewModel.getBook()?.let { book ->
////                if (book.isWebFile) {
////                    showWebFileDownloadAlert {
////                        readBook(it)
////                    }
////                } else {
//                readBook(book)
////                }
//            }
//        }
////        tvShelf.setOnClickListener {
////            viewModel.getBook()?.let { book ->
////                if (viewModel.inBookshelf) {
////                    deleteBook()
////                } else {
////                    if (book.isWebFile) {
////                        showWebFileDownloadAlert()
////                    } else {
////                        viewModel.addToBookshelf {
////                            upTvBookshelf()
////                        }
////                    }
////                }
////            }
////        }
////        tvOrigin.setOnClickListener {
////            viewModel.getBook()?.let { book ->
////                if (book.isLocal) return@let
////                editSourceResult.launch {
////                    putExtra("sourceUrl", book.origin)
////                }
////            }
////        }
////        tvChangeSource.setOnClickListener {
////            viewModel.getBook()?.let { book ->
////                showDialogFragment(ChangeBookSourceDialog(book.name, book.author))
////            }
////        }
//        tvTocView.setOnClickListener {
//
//            LogUtils.e(">>>> ", "chapterListData = " + viewModel.chapterListData.value.toString())
//            if (viewModel.chapterListData.value.isNullOrEmpty()) {
//                toastOnUi(R.string.chapter_list_empty)
//                return@setOnClickListener
//            }
//            toMuLu()
//        }
////        tvChangeGroup.setOnClickListener {
////            viewModel.getBook()?.let {
////                showDialogFragment(
////                    GroupSelectDialog(it.group)
////                )
////            }
////        }
////        tvAuthor.setOnClickListener {
////            viewModel.getBook(false)?.let { book ->
////                startActivity<SearchActivity> {
////                    putExtra("key", book.author)
////                }
////            }
////        }
//        tvName.setOnClickListener {
//            viewModel.getBook(false)?.let { book ->
//                startActivity<SearchActivity> {
//                    putExtra("key", book.name)
//                }
//            }
//        }
//        refreshLayout?.setOnRefreshListener {
//            refreshLayout.isRefreshing = false
//            refreshBook()
//        }
//    }
//
//    private fun toMuLu() {
//        viewModel.getBook()?.let { book ->
//            LogUtils.e(">>>> ", "book = " + book.toString())
//
//            LogUtils.e(">>>> ", "inBookshelf = " + viewModel.inBookshelf)
//            if (!viewModel.inBookshelf) {
//                viewModel.saveBook(book) {
//                    viewModel.saveChapterList {
//                        openChapterList()
//                        LogUtils.e(">>>> ", "openChapterList111111111")
//                    }
//                }
//            } else {
//                LogUtils.e(">>>> ", "openChapterList222222222")
//                openChapterList()
//            }
//        }
//    }
//
////    private fun setSourceVariable() {
////        lifecycleScope.launch {
////            val source = viewModel.bookSource
////            if (source == null) {
////                toastOnUi("书源不存在")
////                return@launch
////            }
////            val comment =
////                source.getDisplayVariableComment("源变量可在js中通过source.getVariable()获取")
////            val variable = withContext(IO) { source.getVariable() }
////            showDialogFragment(
////                VariableDialog(
////                    getString(R.string.set_source_variable),
////                    source.getKey(),
////                    variable,
////                    comment
////                )
////            )
////        }
////    }
//
////    private fun setBookVariable() {
////        lifecycleScope.launch {
////            val source = viewModel.bookSource
////            if (source == null) {
////                toastOnUi("书源不存在")
////                return@launch
////            }
////            val book = viewModel.getBook() ?: return@launch
////            val variable = withContext(IO) { book.getCustomVariable() }
////            val comment =
////                source.getDisplayVariableComment("""书籍变量可在js中通过book.getVariable("custom")获取""")
////            showDialogFragment(
////                VariableDialog(
////                    getString(R.string.set_book_variable),
////                    book.bookUrl,
////                    variable,
////                    comment
////                )
////            )
////        }
////    }
//
////    override fun setVariable(key: String, variable: String?) {
////        when (key) {
////            viewModel.bookSource?.getKey() -> viewModel.bookSource?.setVariable(variable)
////            viewModel.bookData.value?.bookUrl -> viewModel.bookData.value?.let {
////                it.putCustomVariable(variable)
////                viewModel.saveBook(it)
////            }
////        }
////    }
//
////    @SuppressLint("InflateParams")
////    private fun deleteBook() {
////        viewModel.getBook()?.let {
////            if (LocalConfig.bookInfoDeleteAlert) {
////                alert(
////                    titleResource = R.string.draw,
////                    messageResource = R.string.sure_del
////                ) {
////                    var checkBox: CheckBox? = null
////                    if (it.isLocal) {
////                        checkBox = CheckBox(this@BookInfoActivity).apply {
////                            setText(R.string.delete_book_file)
////                            isChecked = LocalConfig.deleteBookOriginal
////                        }
////                        val view = LinearLayout(this@BookInfoActivity).apply {
////                            setPadding(16.dpToPx(), 0, 16.dpToPx(), 0)
////                            addView(checkBox)
////                        }
////                        customView { view }
////                    }
////                    yesButton {
////                        if (checkBox != null) {
////                            LocalConfig.deleteBookOriginal = checkBox.isChecked
////                        }
////                        viewModel.delBook(LocalConfig.deleteBookOriginal) {
////                            finish()
////                        }
////                    }
////                    noButton()
////                }
////            } else {
////                viewModel.delBook(LocalConfig.deleteBookOriginal) {
////                    finish()
////                }
////            }
////        }
////    }
//
//    private fun openChapterList() {
//
//        viewModel.getBook()?.let {
//            LogUtils.e(">>>>> ", "bookUrl = " + it.bookUrl)
//            tocActivityResult.launch(it.bookUrl)
//        }
//    }
//
////    private fun showWebFileDownloadAlert(
////        onClick: ((Book) -> Unit)? = null
////    ) {
////        val webFiles = viewModel.webFiles
////        if (webFiles.isEmpty()) {
////            toastOnUi("Unexpected webFileData")
////            return
////        }
////        selector(
////            R.string.download_and_import_file,
////            webFiles
////        ) { _, webFile, _ ->
////            if (webFile.isSupported) {
////                /* import */
////                viewModel.importOrDownloadWebFile<Book>(webFile) {
////                    onClick?.invoke(it)
////                }
////            } else if (webFile.isSupportDecompress) {
////                /* 解压筛选后再选择导入项 */
////                viewModel.importOrDownloadWebFile<Uri>(webFile) { uri ->
////                    viewModel.getArchiveFilesName(uri) { fileNames ->
////                        if (fileNames.size == 1) {
////                            viewModel.importArchiveBook(uri, fileNames[0]) {
////                                onClick?.invoke(it)
////                            }
////                        } else {
////                            showDecompressFileImportAlert(uri, fileNames, onClick)
////                        }
////                    }
////                }
////            } else {
////                alert(
////                    title = getString(R.string.draw),
////                    message = getString(R.string.file_not_supported, webFile.name)
////                ) {
////                    neutralButton(R.string.open_fun) {
////                        /* download only */
////                        viewModel.importOrDownloadWebFile<Uri>(webFile) {
////                            openFileUri(it, "*/*")
////                        }
////                    }
////                    noButton()
////                }
////            }
////        }
////    }
//
////    private fun showDecompressFileImportAlert(
////        archiveFileUri: Uri,
////        fileNames: List<String>,
////        success: ((Book) -> Unit)? = null
////    ) {
////        if (fileNames.isEmpty()) {
////            toastOnUi(R.string.unsupport_archivefile_entry)
////            return
////        }
////        selector(
////            R.string.import_select_book,
////            fileNames
////        ) { _, name, _ ->
////            viewModel.importArchiveBook(archiveFileUri, name) {
////                success?.invoke(it)
////            }
////        }
////    }
//
//    private fun readBook(book: Book) {
//        if (!viewModel.inBookshelf) {
//            viewModel.saveBook(book) {
//                viewModel.saveChapterList {
//                    startReadActivity(book)
//                }
//            }
//        } else {
//            viewModel.saveBook(book) {
//                startReadActivity(book)
//            }
//        }
//    }
//
//    private fun startReadActivity(book: Book) {
//        when {
//            book.isAudio -> readBookResult.launch(
//                Intent(this, AudioPlayActivity::class.java)
//                    .putExtra("bookUrl", book.bookUrl)
//                    .putExtra("inBookshelf", viewModel.inBookshelf)
//            )
//
//            else -> readBookResult.launch(
//                Intent(this, ReadBookActivity::class.java)
//                    .putExtra("bookUrl", book.bookUrl)
//                    .putExtra("inBookshelf", viewModel.inBookshelf)
//                    .putExtra("tocChanged", tocChanged)
//                    .putExtra("chapterChanged", chapterChanged)
//            )
//        }
//        tocChanged = false
//    }
//
////    override val oldBook: Book?
////        get() = viewModel.bookData.value
////
////    override fun changeTo(source: BookSource, book: Book, toc: List<BookChapter>) {
////        viewModel.changeTo(source, book, toc)
////    }
//
////
////    override fun upGroup(requestCode: Int, groupId: Long) {
//////        upGroup(groupId)
////        viewModel.getBook()?.let { book ->
////            book.group = groupId
////            if (viewModel.inBookshelf) {
////                viewModel.saveBook(book)
////            } else if (groupId > 0) {
////                viewModel.addToBookshelf {
////                    upTvBookshelf()
////                }
////            }
////        }
////    }
//
//    private fun upWaitDialogStatus(isShow: Boolean) {
//        val showText = "Loading....."
//        if (isShow) {
//            waitDialog.run {
//                setText(showText)
//                show()
//            }
//        } else {
//            waitDialog.dismiss()
//        }
//    }

}